//
//  ICEWebViewController.m
//  ICEubLib
//
//  Created by wujianrong on 16/4/20.
//  Copyright © 2016年 wanda. All rights reserved.
//

#import "ICEWebViewController.h"
#import "ICECore.h"
#import "ICENewWebView.h"
#import "ICEUI.h"
#import "ICEJavaScriptBridge.h"
//#import <objc/objc-runtime.h>
#import <objc/message.h>

#define _ICE_NAVGATION_BACK        1
#define _ICE_NAVGATION_CLOSE       2
#define _ICE_NAVGATION_HIDE        3
#define _ICE_NAVGATION_URLSCHEME   4
#define _ICE_NAVGATION_RELOAD      5
#define _ICE_NAVGATION_WEBURL      6
#define _ICE_NAVGATION_CALLBACK    7
#define screen_height  [UIScreen mainScreen].bounds.size.height

@interface ICEWebViewController() <WKUIDelegate>
{
    NSInteger _leftTopAction;
    NSString* _leftUrl;
    NSInteger _rightTopAction;
    NSString* _rightUrl;
    
    ICENavigatorBar* _nvBar;
    
    NSDictionary* _jsArgs;
}
@end

@implementation ICEWebViewController

-(instancetype)initWithUrl:(NSString*)url
{
    self = [super init];
    if (self) {
        _url = ICESafeString(url);
    }
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    _leftTopAction = _ICE_NAVGATION_CLOSE;
    _rightTopAction = _ICE_NAVGATION_HIDE;
    __weak typeof(self) Weakself = self;
    
    _nvBar = [[ICENavigatorBar alloc]init];
    if (isIphoneX) {
        _nvBar.frame = CGRectMake(0, 0, ICESCREEN_WIDTH, 88);
    }
    else{
        _nvBar.frame = CGRectMake(0, 0, ICESCREEN_WIDTH, 64);
    }
    _nvBar.leftClickBlock = ^(){
        [Weakself leftTopAction:nil];
    };
    _nvBar.rightClickBlock = ^(){
        [Weakself rightTopAction:nil];
    };
    if (_config ) {
        _nvBar.config = _config;
    }
    [_nvBar setupUI];
    [self.view addSubview:_nvBar];
    [self leftNavigationItemWithObject:NSLocalizedString(@"返回", nil) right:nil title:NSLocalizedString(@"加载中", nil)];
    ICENewWebView* webView = [[ICENewWebView alloc]init];
    if (isIphoneX) {
        webView.frame = CGRectMake(0, 88, ICESCREEN_WIDTH, ICESCREEN_HEIGHT - 88-34);
    }
    else{
       webView.frame = CGRectMake(0, 64, ICESCREEN_WIDTH, ICESCREEN_HEIGHT - 64);
    }
    webView.url = [NSURL URLWithString:_url];
    if (_userAgent) {
        webView.userAgent = _userAgent;
    }
    webView.vc = self;
    [webView beginBrowse];
    webView.webView.UIDelegate = self;
    [self.view addSubview:webView];
    _webView = webView;
}

-(void)leftTopAction:(id)sender
{
    switch (_leftTopAction) {
        case _ICE_NAVGATION_CLOSE:
        {
            if ([_webView respondsToSelector:@selector(closeWebAction)]) {
                [_webView performSelector:@selector(closeWebAction)];
            }
        }
            break;
 
        case _ICE_NAVGATION_BACK:
        {
            if ([_webView respondsToSelector:@selector(webBack)]) {
                [_webView performSelector:@selector(webBack)];
            }
        }
            break;
            
        case _ICE_NAVGATION_HIDE:
        {
            [self leftNavigationItemWithObject:@"" right:nil title:nil];
        }
            break;
            
        case _ICE_NAVGATION_RELOAD:
        {
            if ([_webView respondsToSelector:@selector(refreshWebView)]) {
                [_webView performSelector:@selector(refreshWebView)];
            }
        }
            break;
        case _ICE_NAVGATION_URLSCHEME:
        {
            if (ICESafeString(_leftUrl).length > 4) {
                Class cls = objc_getMetaClass("ICEEMUrlScheme");
                if (cls != NULL) {
                    if (class_respondsToSelector(cls, @selector(openURL:))) {
                        ((void(*)(id, SEL, NSObject*))objc_msgSend)(NSClassFromString(@"ICEEMUrlScheme"), @selector(openURL:), ICESafeString(_leftUrl));
                    }
                }
               
            }
        }
            break;
        case _ICE_NAVGATION_WEBURL:
        {
            if ([_webView respondsToSelector:@selector(loadNewRequestWithUrl:)]) {
                [_webView performSelector:@selector(loadNewRequestWithUrl:) withObject:ICESafeString(_leftUrl)];
            }
        }
            break;
            
        case _ICE_NAVGATION_CALLBACK:
        {
            NSDictionary* ret = @{
                                  @"status":@"success",
                                  @"source":@"left",
                                  };
            [ICEJavaScriptBridge sendReslutToJS:ret callInfo:_jsArgs];
        }
            break;
        default:
        {
            
        }
            break;
    }
}

-(void)rightTopAction:(id)sender
{
    switch (_rightTopAction) {
        case _ICE_NAVGATION_CLOSE:
        {
            if ([_webView respondsToSelector:@selector(closeWebAction)]) {
                [_webView performSelector:@selector(closeWebAction)];
            }
        }
            break;
            
        case _ICE_NAVGATION_BACK:
        {
            if ([_webView respondsToSelector:@selector(webBack)]) {
                [_webView performSelector:@selector(webBack)];
            }
        }
            break;
            
        case _ICE_NAVGATION_HIDE:
        {
            [self leftNavigationItemWithObject:nil right:nil title:@" "];
        }
            break;
            
        case _ICE_NAVGATION_RELOAD:
        {
            if ([_webView respondsToSelector:@selector(refreshWebView)]) {
                [_webView performSelector:@selector(refreshWebView)];
            }
        }
            break;
        case _ICE_NAVGATION_URLSCHEME:
        {
            if (ICESafeString(_rightUrl).length > 4) {
                Class cls = objc_getMetaClass("ICEEMUrlScheme");
                if (cls != NULL) {
                    if (class_respondsToSelector(cls, @selector(openURL:))) {
                        ((void(*)(id, SEL, NSObject*))objc_msgSend)(NSClassFromString(@"ICEEMUrlScheme"), @selector(openURL:), ICESafeString(_rightUrl));
                    }
                }
                
            }
        }
            break;
        case _ICE_NAVGATION_WEBURL:
        {
            if ([_webView respondsToSelector:@selector(loadNewRequestWithUrl:)]) {
                [_webView performSelector:@selector(loadNewRequestWithUrl:) withObject:ICESafeString(_rightUrl)];
            }
        }
            break;
            
        case _ICE_NAVGATION_CALLBACK:
        {
            NSDictionary* ret = @{
                                  @"status":@"success",
                                  @"source":@"right",
                                  };
            [ICEJavaScriptBridge sendReslutToJS:ret callInfo:_jsArgs];
        }
            break;
        default:
        {
            
        }
            break;
    }
}

-(void)leftNavigationItemWithObject:(NSObject*)left right:(NSObject*)right title:(NSObject*)title
{
    [_nvBar setLeftNavigationItemWithStr:left right:right title:title status:nil];
}

-(void)closeWebAction
{
    if (self.navigationController == nil) {
        [self dismissViewControllerAnimated:YES completion:nil];
        return;
    }
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)webBack
{
    if ([_webView respondsToSelector:@selector(webBack)]) {
        [_webView performSelector:@selector(webBack)];
    }
}

-(void)refreshWebView
{
    if ([_webView respondsToSelector:@selector(refreshWebView)]) {
        [_webView performSelector:@selector(refreshWebView)];
    }
}


-(void)updateNavigationBarWithLeftTitle:(NSString *)leftTitle leftAction:(NSString *)leftAction rightTitle:(NSString *)rightTitle rightAction:(NSString *)rightAction navigatorTitle:(NSString *)navigatorTitle leftUrl:(NSString *)leftUrl rightUrl:(NSString *)rightUrl navigationBarStatus:(NSString *)status args:(NSDictionary*)arg
{
    _jsArgs = arg;
    //left button action
    if ([ICESafeString(leftAction) isEqualToString:@"close"]) {
        _leftTopAction = _ICE_NAVGATION_CLOSE;
    }
    
    if ([ICESafeString(leftAction) isEqualToString:@"back"]) {
        _leftTopAction = _ICE_NAVGATION_BACK;
        //   [self setBackWithTitle:@" "];
    }
    
    if ([ICESafeString(leftAction) isEqualToString:@"null"]) {
        _leftTopAction = _ICE_NAVGATION_HIDE;
        leftTitle = @" ";
    }
    
    if ([ICESafeString(leftAction) isEqualToString:@"reload"]) {
        _leftTopAction = _ICE_NAVGATION_RELOAD;
    }
    
    if ([ICESafeString(leftAction) isEqualToString:@"url"]) {
        _leftTopAction = _ICE_NAVGATION_URLSCHEME;
        _leftUrl = leftUrl;
    }
    //weburl
    if ([ICESafeString(leftAction) isEqualToString:@"weburl"]) {
        _leftTopAction = _ICE_NAVGATION_WEBURL;
        _leftUrl = leftUrl;
    }
    
    if ([ICESafeString(leftAction) isEqualToString:@"callback"]) {
        _leftTopAction = _ICE_NAVGATION_CALLBACK;
        _leftUrl = leftUrl;
    }
    
    
    /**
     *  right button action
     */
    if ([ICESafeString(rightAction) isEqualToString:@"close"]) {
        _rightTopAction = _ICE_NAVGATION_CLOSE;
    }
    
    if ([ICESafeString(rightAction) isEqualToString:@"back"]) {
        _rightTopAction = _ICE_NAVGATION_BACK;
    }
    
    if ([ICESafeString(rightAction) isEqualToString:@"null"]) {
        _rightTopAction = _ICE_NAVGATION_HIDE;
        rightTitle = @" ";
    }
    
    if ([ICESafeString(rightAction) isEqualToString:@"reload"]) {
        _rightTopAction = _ICE_NAVGATION_RELOAD;
    }
    
    if ([ICESafeString(rightAction) isEqualToString:@"url"]) {
        _rightTopAction = _ICE_NAVGATION_URLSCHEME;
        _rightUrl = rightUrl;
    }
    
    if ([ICESafeString(rightAction) isEqualToString:@"weburl"]) {
        _rightTopAction = _ICE_NAVGATION_WEBURL;
        _rightUrl = rightUrl;
    }
    
    if ([ICESafeString(rightAction) isEqualToString:@"callback"]) {
        _rightTopAction = _ICE_NAVGATION_CALLBACK;
        _rightUrl = rightUrl;
    }
    
    if ([ICESafeString(leftTitle) isEqualToString:@"<"]) {
        [_nvBar setBackWithTitle:@" "];
        leftTitle = nil;
    }
    [self leftNavigationItemWithObject:((ICESafeString(leftTitle).length > 0)?(ICESafeString(leftTitle)):nil) right:((ICESafeString(rightTitle).length > 0)?(ICESafeString(rightTitle)):nil) title:((ICESafeString(navigatorTitle).length > 0)?(ICESafeString(navigatorTitle)):nil)];
}

#pragma mark - WKUIDelegate
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"提示",nil) message:message?:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:([UIAlertAction actionWithTitle:NSLocalizedString(@"确认", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler();
    }])];
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL result))completionHandler
{
    //    DLOG(@"msg = %@ frmae = %@",message,frame);
      UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"提示",nil) message:message?:@"" preferredStyle:UIAlertControllerStyleAlert];
      [alertController addAction:([UIAlertAction actionWithTitle:NSLocalizedString(@"取消", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
          completionHandler(NO);
      }])];
      [alertController addAction:([UIAlertAction actionWithTitle:NSLocalizedString(@"确认", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
          completionHandler(YES);
      }])];
      [self presentViewController:alertController animated:YES completion:nil];
}

- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * _Nullable))completionHandler{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:prompt message:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.text = defaultText;
    }];
    [alertController addAction:([UIAlertAction actionWithTitle:NSLocalizedString(@"完成", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(alertController.textFields[0].text?:@"");
    }])];


    [self presentViewController:alertController animated:YES completion:nil];
}

@end


@implementation ICEWebInfo

@end

